package com.wj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wj.dto.PagingDTO;
import com.wj.mapper.ArticleMapper;
import com.wj.pojo.Article;
import com.wj.service.IArticleService;
import com.wj.utils.RespBean;
import com.wj.utils.UserUtil;
import com.wj.vo.PagingVO;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wj
 * @since 2022-05-31
 */
@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements IArticleService {

    @Resource
    private ArticleMapper articleMapper;

    /**
     * 添加文章
     *
     * @param article
     * @return
     */
    @Override
    public RespBean addArticle(Article article) {
        article.setUserId(UserUtil.getCurrentUser().getId());
        if (articleMapper.insert(article) > 0) {
            return RespBean.success("添加成功");
        }
        return RespBean.error("添加失败");
    }

    /**
     * 获取分页的文章
     *
     * @param pagingVO
     * @return
     */
    @Override
    public RespBean getPagingArticle(PagingVO pagingVO) {
        Integer count = articleMapper.selectCountArticle(pagingVO);
        if (count > 0) {
            pagingVO.setStartPageSize((pagingVO.getCurrentPage() - 1) * pagingVO.getPageSize());
            List<Article> articles = articleMapper.getPagingArticle(pagingVO, UserUtil.getCurrentUser().getId());
            return RespBean.success("成功", PagingDTO.builder().count(count).object(articles).build());
        }
        return RespBean.error();
    }

    /**
     * 首页展示文章
     *
     * @param pagingVO
     * @return
     */
    @Override
    public RespBean getHomeArticles(PagingVO pagingVO) {
        Integer count = articleMapper.selectCountArticle(pagingVO);
        if (count > 0) {
            pagingVO.setStartPageSize((pagingVO.getCurrentPage() - 1) * pagingVO.getPageSize());
            List<Article> articles = articleMapper.getPagingArticle(pagingVO, 200);
            return RespBean.success("成功", PagingDTO.builder().count(count).object(articles).build());
        }
        return RespBean.error();
    }

    /**
     * 根据id获取对应文章
     *
     * @param id
     * @return
     */
    @Override
    public RespBean getArticleById(Integer id) {
        Article article = articleMapper.selectOne(
                new QueryWrapper<Article>()
                        .eq("id", id)
                        .eq("is_draft", false)
                        .eq("is_delete", false)
                        .eq("is_private", false)
        );
        if (!ObjectUtils.isEmpty(article)){
            return RespBean.success(article);
        }
        return RespBean.error();
    }
}
